package com.santiao.youxiang.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.CheckBox
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.gyf.immersionbar.ImmersionBar
import com.santiao.publics.ui.SettingFragment
//import com.lazyliuzy.commonui.utils.lzy.LZYADSUtils
import kotlin.apply
//import kotlin.jvm.java
import com.santiao.youxiang.R
import com.santiao.youxiang.database.habitBill
import com.santiao.youxiang.database.habitBill.Weekly

import com.santiao.youxiang.databinding.ActivityHabitCreateBinding
import com.santiao.youxiang.ext.thrillClickListener
import org.litepal.LitePal
import java.time.LocalDateTime
import kotlin.collections.ArrayList

class HabitEditActivity: AppCompatActivity() {
    private lateinit var binding: ActivityHabitCreateBinding
//    private lateinit var lzyadsUtils: com.lazyliuzy.commonui.utils.lzy.LZYADSUtils
var type_a="" //1 新建 2：编辑
    var imageType_a="" //1 阅读 2：早睡 3：早起 4：喝水 0：运动
    var uid_a="" //数据库 id

    var weekList :ArrayList<Weekly?>?=null

    var remindSwitch=0

    var slePosition=1

    var struri=""
    // 在类顶部定义
    val REQUEST_STORAGE_PERMISSION = 1001  // 可以是任意唯一整数

    companion object {
        // 定义一个静态方法来创建Intent
        // 定义一个静态方法来创建Intent并携带uri数据
        fun startActivity(context: Context?, type: String, /*imageType: String,*/ uid: String) {

            val intent = Intent(context, HabitEditActivity::class.java).apply {

                putExtra("type", type)
//                putExtra("imageType", imageType)
                putExtra("uid", uid)

            }

            context!!.startActivity(intent)
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHabitCreateBinding.inflate(layoutInflater)
        setContentView(binding?.root)
        type_a= intent.getStringExtra("type").toString()
        uid_a= intent.getStringExtra("uid").toString()
//        imageType_a= intent.getStringExtra("imageType").toString()

        ImmersionBar.with(this)
            .transparentStatusBar()
            .statusBarDarkFont(true)
            .transparentNavigationBar()
            .init()
        initViews(type_a)


        SettingFragment.adLoad2(0,null,binding.flContent22,this,this);
    }



     fun initViews(type: String) {
//        initad()
         when(type){
             "1"->{
                 binding.tvTitle.text="新建习惯"
             }

             "2"->{
                 initdata()
             }

         }

         initclick()


       binding.pkTime.setIs24HourView(true)





    }

    fun initclick(){
        binding.ivBack.setOnClickListener { onBackPressed() }
        binding.ivSwitch.thrillClickListener {
            if (remindSwitch==0){
                binding.ivSwitch.setImageResource(R.drawable.ic_habit_on)
                remindSwitch=1
            }else{
                remindSwitch=0
                binding.ivSwitch.setImageResource(R.drawable.ic_habit_off)
            }
//            AddAccountActivity.startActivity(this,"1")
        }


        binding.tvSave.thrillClickListener{
            if (binding.etName.text.isNullOrBlank()){
                Toast.makeText(this@HabitEditActivity,"请填写习惯名称", Toast.LENGTH_LONG).show()
                return@thrillClickListener
            }

            if (binding.etObjectTimes.text.isNullOrBlank()){
                Toast.makeText(this@HabitEditActivity,"请填写单日目标次数", Toast.LENGTH_LONG).show()
                return@thrillClickListener
            }

            if (binding.etObjectDay.text.isNullOrBlank()){
                Toast.makeText(this@HabitEditActivity,"请填写目标天数", Toast.LENGTH_LONG).show()
                return@thrillClickListener
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                saveHabit()
            }

        }


    }

    fun switchItem(position: Int) {

    }



    @SuppressLint("NewApi")
    @RequiresApi(Build.VERSION_CODES.M)
    fun saveHabit(){
        weekList = ArrayList<Weekly?>()
        weekList?.clear()
        var week:Weekly?=null
        week=Weekly()
        for (i in 1..7) {
            // 根据名称动态获取资源 id
            val resId = resources.getIdentifier("ck$i", "id", packageName)
//                    val resIdtv = resources.getIdentifier("tv_month$i", "id", packageName)
            // findViewById 或者如果你用的是 ViewBinding 用 binding.root.findViewById(...)
            val checkView = findViewById<CheckBox>(resId) ?: continue
//                    val monthtv = findViewById<TextView>(resIdtv) ?: continue
            if (checkView.isChecked){
                week!!.sate="1"
            }else{
                week!!.sate="0"
            }
            weekList!!.add(i-1,week)
        }
        Log.e("saveHabit: ",weekList.toString() )
        var current = LocalDateTime.now()

        val year = current.year
        val monthValue = current.monthValue
        val dayOfMonth = current.dayOfMonth

        val hour = current.hour
        val minute = current.minute
        val second = current.second

        var updateTime="$year-$monthValue-$dayOfMonth $hour:$minute:$second"

        when (type_a){

            "1"->{

                var habitob= habitBill(habitName = binding.etName.text.toString().trim(),habitToday_target=binding.etObjectTimes.text.toString().trim(),
                    habitTargetDay=binding.etObjectDay.text.toString().trim(),habitRemind=remindSwitch.toString(),
                    RemindTime=binding.pkTime.hour.toString()+":"+binding.pkTime.minute,habitWeekly=weekList, update = updateTime)

                Log.e("saveHabit: ",habitob.toString() )

//                Log.e( "saveBill: ", "billType "+slePosition+" "+binding.etAmout.text.toString()+"  "+binding.tvDate.text.toString())
                try {
                    habitob.save()
                }catch (e: Exception){
                    Log.e( "saveBill: ", e.toString())
                }
                if (habitob.save()){
                    Toast.makeText(this@HabitEditActivity,"保存成功", Toast.LENGTH_LONG).show()
                    onBackPressed()
                }else Toast.makeText(this@HabitEditActivity,"保存失败", Toast.LENGTH_LONG).show()
            }

            "2"->{
                var hab = LitePal.where("id = ?", uid_a).findFirst(habitBill::class.java)
                hab.habitName=binding.etName.text.toString()
                hab.habitToday_target=binding.etObjectTimes.text.toString()
                hab.habitTargetDay=binding.etObjectDay.text.toString()
                hab.RemindTime=binding.pkTime.hour.toString()+":"+binding.pkTime.minute
                hab.habitWeekly=weekList
                hab.update=updateTime
                hab.habitRemind=remindSwitch.toString()
//                hab= habitBill(habitName = binding.etName.text.toString().trim(),habitToday_target=binding.etObjectTimes.text.toString().trim(),
//                    habitTargetDay=binding.etObjectDay.text.toString().trim(),habitRemind=remindSwitch.toString(),
//                    RemindTime=binding.pkTime.hour.toString()+":"+binding.pkTime.minute,habitWeekly=weekList,update = updateTime)
                if (hab.save()){
                    Toast.makeText(this@HabitEditActivity,"保存成功", Toast.LENGTH_LONG).show()
                    onBackPressed()
                }else Toast.makeText(this@HabitEditActivity,"保存失败", Toast.LENGTH_LONG).show()
            }

        }

    }

   fun initdata(){
       var hab = LitePal.where("id = ?", uid_a).findFirst(habitBill::class.java)

       binding.etName.setText(hab.habitName.toString())
       binding.etObjectTimes.setText(hab.habitToday_target.toString())
       binding.etObjectDay.setText(hab.habitTargetDay.toString())

       if (hab.habitRemind?.toInt()==1){
           binding.ivSwitch.performClick()
       }


    }


    fun   initad() {
//        myContext = requireContext()
//        lzyadsUtils=
//            com.lazyliuzy.commonui.utils.lzy.LZYADSUtils("Task1Activity", this@Task1Activity)
//        com.lazyliuzy.commonui.utils.lzy.LZYADSUtils.loadSimpleAd1(com.lazyliuzy.commonui.databinding.ActivityTask1Binding.flAd)
//        com.lazyliuzy.commonui.utils.lzy.LZYADSUtils.showAdCpTurn()

    }

}